/*
 * Copyright 2010 Beijing Xinwei, Inc. All rights reserved.
 *
 * History:
 * ------------------------------------------------------------------------------
 * Date    	|  Who  		|  What
 * 2016-2-24	| duanbokan 	| 	create the file
 */

package com.yh.tess.constant;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.util.Log;


import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.IOException;

/**
 *
 * 类简要描述
 *
 * <p>
 * 类详细描述
 * </p>
 *
 * @author duanbokan
 *
 */

public class ParseImage {
	private static final String TAG = "ParseImage";

	private static ParseImage instance;

	public static ParseImage getInstance() {
		if (instance == null)
		{
			instance = new ParseImage();
		}
		return instance;
	}

	/**
	 * 识别图片中文字,需要放入异步线程中进行执行
	 *
	 * @param
	 * @return
	 * @throws IOException
	 */
	public String parseImageToString(String imagePath) throws IOException {
		// 检验图片地址是否正确
		if (imagePath == null || imagePath.equals("")) {
			return TessErrorCode.IMAGE_PATH_IS_NULL;
		}

		// 获取Bitmap
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

		// 图片旋转角度
		int rotate = 0;

		ExifInterface exif = new ExifInterface(imagePath);

		// 先获取当前图像的方向，判断是否需要旋转
		int imageOrientation = exif
				.getAttributeInt(ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_NORMAL);

		Log.i(TAG, "Current image orientation is " + imageOrientation);

		switch (imageOrientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				rotate = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				rotate = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				rotate = 270;
				break;
			default:
				break;
		}

		Log.i(TAG, "Current image need rotate: " + rotate);

		// 获取当前图片的宽和高
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();

		// 使用Matrix对图片进行处理
		Matrix mtx = new Matrix();
		mtx.preRotate(rotate);

		// 旋转图片
		bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
		bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

		// 开始调用Tess函数对图像进行识别
		TessBaseAPI baseApi = new TessBaseAPI();
		baseApi.setDebug(true);
		// 使用默认语言初始化BaseApi
		baseApi.init(TessConstantConfig.TESSBASE_PATH,
				TessConstantConfig.DEFAULT_LANGUAGE_ENG);
		baseApi.setImage(bitmap);

		// 获取返回值
		String recognizedText = baseApi.getUTF8Text();
		baseApi.end();
		return recognizedText;
	}
}
